#include "opacitymoveeater.h"
#include "mouseeater.h"
#include <QEasingCurve>
#include <QPropertyAnimation>

OpacityMoveEater::OpacityMoveEater(QWidget *parent, QWidget *target)
    : QObject{}
    , m_target(parent)
    , m_opacity(0.95)
{

    if (target != nullptr) {
        m_target = target;
    }

    new MouseEater([this](QMouseEvent * event)
    {
        static QPoint mousePoint;
        static bool mousePressed = false;
        static QPropertyAnimation animation(m_target, "windowOpacity");
        animation.setEasingCurve(QEasingCurve::InQuart);

        if (event->type() == QMouseEvent::MouseButtonPress)
        {
            mousePressed = true;
            mousePoint = event->globalPos() - m_target->pos();
        }
        else if (event->type() == QMouseEvent::MouseButtonRelease)
        {
            mousePressed = false;
            animation.stop();
            animation.setStartValue(m_target->windowOpacity());
            animation.setEndValue(1.0);
            animation.start();
        }
        else if (event->type() == QMouseEvent::MouseMove)
        {
            if (mousePressed && (event->buttons() & Qt::LeftButton))
            {
                m_target->move(event->globalPos() - mousePoint);
                animation.setStartValue(m_target->windowOpacity());
                animation.setEndValue(m_opacity);
                animation.start();
                return true;
            }
        }
        return false;
    }, parent);
}

void OpacityMoveEater::setOpacity(double newOpacity)
{
    m_opacity = newOpacity;
}
